package xyz.weizhi.tanhua.appserver.service;

import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import xyz.weizhi.tanhua.appserver.interceptor.UserHolder;
import xyz.weizhi.tanhua.dubbo.api.RecommendUserApi;
import xyz.weizhi.tanhua.dubbo.api.UserInfoApi;
import xyz.weizhi.tanhua.model.Dto.RecommendUserDto;
import xyz.weizhi.tanhua.model.domain.UserInfo;
import xyz.weizhi.tanhua.model.mongo.RecommendUser;
import xyz.weizhi.tanhua.model.vo.PageResult;
import xyz.weizhi.tanhua.model.vo.TodayBest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author milian
 * @Date 2021/10/24 0024 19:48
 */
@Service
public class TanhuaService {
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    public TodayBest todayBest() {
        // 获取用户id
        Long userId = UserHolder.getId();
        // 查询今日最佳
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if (recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
        return todayBest;
    }

    public PageResult recommendation(RecommendUserDto recommendUser) {
        // 获取用户id
        Long userId = UserHolder.getId();
        PageResult pageResult = recommendUserApi.queryAll(recommendUser.getPage(), recommendUser.getPagesize(), userId);
        List<RecommendUser> items = (List<RecommendUser>) pageResult.getItems();
        if (items==null||items.size()<=0){
            return pageResult;
        }
        // 获取所有推荐用户id
        ArrayList<Long> userIds = new ArrayList<>();
        items.stream().forEach(e->{
            userIds.add(e.getUserId());
        });
        UserInfo userInfo = new UserInfo();
        userInfo.setGender(recommendUser.getGender());
        userInfo.setAge(recommendUser.getAge());
        // 批量查询用户信息
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(userIds, userInfo);
        ArrayList<TodayBest> todayBests = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo userinfo1 = userInfoMap.get(item.getUserId());
            if (userinfo1!=null){
                TodayBest vo = TodayBest.init(userinfo1, item);
                todayBests.add(vo);
            }
        }
        pageResult.setItems(todayBests);
        return pageResult;

    }
}
